package com.xzk.gateway.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Classname MyGlobalFilter
 * @Description TODO
 * @Date 2020/9/23 21:28
 * @Created by ccc-j
 * @email ccc-ju@outlook.com
 */
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        System.out.println("全局过滤器");
        String token = exchange.getRequest().getHeaders().getFirst("token");
        //没有token的情况
        if(StringUtils.isBlank(token)){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        //token存在的情况
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        //值越小，优先级越高
        return 1;
    }
}
